package com.openapi.protocol.decode.subPackageHandle.deviceInput;

import com.openapi.data.JT808PackageData;
import com.openapi.data.JT808PushData;
import com.openapi.protocol.decode.subPackageHandle.SubPackageHandle;
import com.openapi.protocol.decode.subPackageHandle.SubPackageStatus;
import com.openapi.protocol.encode.PackageQingdao;
import exsun.jt808.data.config.jt808.Jt808DistributeMsgTopic;
import exsun.jt808.data.distribute_data.Qingdao.DeviceInput;
import exsun.jt808.data.upload_data.Qingdao.DeviceInputResponse;

import exsun.jt808.data.util.parse.DecoderUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 设备录入驾驶员信息上报平台解析
 */
@Component
public class DeviceInputResponseHandle extends SubPackageHandle {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public String getPakKey(JT808PackageData data) {
        return data.dvo +"_"+ data.msgSerialNo;
    }

    @Override
    public DeviceInputResponse parse(JT808PackageData data, byte[] totalBodys) {
        DeviceInputResponse obj = new DeviceInputResponse();
        super.setResultObj(obj,data,Jt808DistributeMsgTopic.DeviceInput_Send);
        int m = DecoderUtils.parseIntFromBytes(totalBodys,0,1);
        obj.setDriverId(DecoderUtils.parseStringFromBytes(totalBodys,1,m));
        int n = DecoderUtils.parseIntFromBytes(totalBodys,1+m,1);
        obj.setJobSeniorityCard(DecoderUtils.parseBcdStringFromBytes(totalBodys,2+m,n));
        int L = DecoderUtils.parseIntFromBytes(totalBodys,2+m+n,1);
        obj.setDriverName(DecoderUtils.parseStringFromBytes(totalBodys,3+m+n,L));
        int h = DecoderUtils.parseIntFromBytes(totalBodys,3+m+n+L,1);
        obj.setFacePictureId(DecoderUtils.parseStringFromBytes(totalBodys,4+m+n+L,h));
        obj.setPictureFormat(DecoderUtils.parseIntFromBytes(totalBodys,4+m+n+L+h,1));
        obj.setPicturePackage(DecoderUtils.byteCopy(totalBodys,5+m+n+L+h,totalBodys.length-(5+m+n+L+h)));

        return obj;
    }

    /**
     * 设备录入驾驶员信息上报平台
     */
    private List<JT808PushData> rsp(JT808PackageData data){
        List<JT808PushData> list = new ArrayList<>();
        List<Integer> miss = super.getMissItems(data);
        JT808PackageData firstPak = super.getPakage(data, 1);
        if(firstPak==null)return list;
        int orgSerialNum = DecoderUtils.parseIntFromBytes(firstPak.getBodyBuffers(), 0, 4);
        DeviceInput rep = new DeviceInput(orgSerialNum, miss);
        JT808PushData body = PackageQingdao.deviceInput(rep);
        list.add(body);
        return list;
    }

    public List<JT808PushData> decode(JT808PackageData data){
        logger.info("接收多媒体数据：{}，{}，{}，{}",data.dvo, data.packageIndex, data.packageSize,data.msgSerialNo);
        List<JT808PushData> list =  new ArrayList<>();
        try {
            SubPackageStatus status = super.append(data);
            String key = getPakKey(data);
            // 检查缺失项，无缺失项,处理数据:存储、推送、应答
            if(status == SubPackageStatus.complete){
                //图片数据上传【完成】应答
                List<JT808PushData> bodys = rsp(data);
                list.addAll(bodys);
                byte[] totalBytes = super.getAllData(data);
                finished(data,  totalBytes);
                super.remove(key);
            }
            if(status == SubPackageStatus.receiving){
                //图片数据上传【通用】应答
                list.add(super.Response(data));
            }
            if(status == SubPackageStatus.missing){
                //图片数据上传【缺失】应答
                List<JT808PushData> bodys = rsp(data);
                list.addAll(bodys);
            }
            return list;
        }catch (Exception e){
            logger.error("图片数据解析异常：{}"+e.getMessage());
        }
        return list;
    }

    private void finished(JT808PackageData data, byte[] totalBytes) throws Exception{
        //存储到ftp服务器
        DeviceInputResponse sendData = parse(data, totalBytes);
        String filePath = DeviceInputPictureHandle.getFilePath(sendData.dvo);
        String fileName = DeviceInputPictureHandle.getFileName();
        String path = "ftp://" + jt808ServerConfig.getJt808FtpServer() + ":" + jt808ServerConfig.getJt808FtpPort() + filePath + "/" + fileName;
        logger.info("人脸图片存储至ftp...  {}", path);
        boolean result = DeviceInputPictureHandle.saveToFTP(super.jt808ServerConfig, fileName, filePath, sendData.getPicturePackage());
        logger.info("人脸图片存储" + (result == true?"成功:":"失败:") + path);
        //推送数据
        super.kafkaService.push(sendData);
    }


}
